package com.cn.study.tool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

/**
 * @author mjy
 * @date 2021/12/28
 * @description
 */
public class JwtTokeUtil {


    private static final String TOKEN_SECRET = "mjycsjwt";  //密钥盐

    /**
     * @param key
     * @param value(key对应的value值,根据不同的value值会生成不同的签名)
     * @param expireTime(过期时间)
     * @return
     */
    public static String sign(String key, String value, Long expireTime) {

        try {
            Date date = new Date(System.currentTimeMillis() + expireTime);
            if (expireTime == null || expireTime < 1) {
                sing(key, value);
            }
            return JWT.create()
                    .withClaim(key, value)
                    .withExpiresAt(date)
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (JWTCreationException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取签名
     *
     * @param key
     * @param value
     * @return
     */
    public static String sing(String key, String value) {
        try {
            return JWT.create()
                    .withClaim(key, value)
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (JWTCreationException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从签名中获取存储key值的value
     *
     * @param sing
     * @param key
     * @return
     */
    public static<T> T getValue(String sing, String key,Class<T> tClass) {
        if (StringUtils.isBlank(sing)||StringUtils.isBlank(key)) {
            return null;
        }
        try {
            DecodedJWT jwt =
                    JWT.decode(sing);
            return jwt.getClaim(key).as(tClass);
        } catch (JWTDecodeException e) {
            e.printStackTrace();
        }
        return null;
    }

}
